package com.baizhi.controller;

import com.baizhi.entity.Picture;
import com.baizhi.entity.Product;
import com.baizhi.entity.Result;
import com.baizhi.service.AdminService;
import com.baizhi.service.PictureService;
import com.baizhi.service.ProductService;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("product")
public class ProductController {

    @Autowired
    public ProductService productService;
    @Autowired
    public PictureService pictureService;

    @Autowired
    public AdminService adminService;

    @RequestMapping("findAll")
    @ResponseBody
    public List<Product> findAll(){
        return  productService.findAll();
    }

    @RequestMapping("showAll")
    @ResponseBody
    public List<Product> showAll(String type){
        return productService.showAll(type);
    }

    @RequestMapping("findById")
    @ResponseBody
    public Product findById(String id){
        return productService.findById(id);
    }

    @RequestMapping("save")
    @ResponseBody
    public Result save(Product product, MultipartFile[] productimage, HttpServletRequest request){
        if("".equals(product.getCatalogid()))
            product.setCatalogid(null);

        Result result = null;
        try{
            String realPath = request.getSession().getServletContext().getRealPath("/back/image/picture");
            String uuid = UUID.randomUUID().toString();
            product.setId(uuid);
            productService.save(product);
            Picture picture = new Picture();
            for (MultipartFile multipartFile : productimage) {
                String uuid1 = UUID.randomUUID().toString();
                String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
                String urlname = uuid1+"."+extension;
                String path = "/back/image/picture/"+urlname;
                picture.setId(uuid1);
                picture.setPath(path);
                picture.setProductid(uuid);
                pictureService.save(picture);
                multipartFile.transferTo(new File(realPath,urlname));
            }
            result = new Result();
            result.setStatus(true);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result();
            result.setMessage("添加成功");
        }
        return  result;
    }

    @RequestMapping("update")
    @ResponseBody
    public Result update(MultipartFile[] productimage,Product product,HttpServletRequest request){
        Result result = null;
        try{
            if(productimage.length!=0){
                String realPath = request.getSession().getServletContext().getRealPath("/back/image/picture");
                List<Picture> byId = pictureService.findById(product.getId());
                for (MultipartFile multipartFile : productimage) {
                    for (Picture picture : byId) {
                        System.out.println(multipartFile.getOriginalFilename()+"======="+picture.getPath());
                        String urlname=picture.getId()+"."+FilenameUtils.getExtension(multipartFile.getOriginalFilename());
                        multipartFile.transferTo(new File(realPath,urlname));
                    }
                }

            }
            productService.update(product);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result();
            result.setMessage("更新失败");
        }
        return result;
    }

    @RequestMapping("delete")
    @ResponseBody
    public Result delete(String id,HttpServletRequest request){
        Result result = null;
        try{
            List<Picture> pictureList = pictureService.findById(id);
            for (Picture picture : pictureList) {
                String realPath = request.getSession().getServletContext().getRealPath(picture.getPath());
                File file = new File(realPath);
                file.delete();
                pictureService.delete(picture.getId());
            }
            productService.delete(id);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result();
            result.setMessage("删除失败");
        }
        return result;
    }

    @RequestMapping("poi")
    @ResponseBody
    public String poi()throws Exception {
        List<Product> products = productService.findAll();

        Field[] declaredFields = Product.class.getDeclaredFields();
        //创建hssfworkbook
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建工作簿
        HSSFSheet sheet = workbook.createSheet("商品信息汇总");

        //合并单元格
        //参数1:起始行 参数2:结束行  参数3:起始列  参数4:结束列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, declaredFields.length-1));
        //修改行间距
        sheet.setDefaultColumnWidth(18);

        //创建标题行
        HSSFRow row = sheet.createRow(0);
        //创建标题列
        HSSFCell cell = row.createCell(0);


        //创建单元格样式
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置对齐方式

        HSSFFont font = workbook.createFont(); //创建字符
        font.setFontHeightInPoints((short) 18);//设置字体大小
        cellStyle.setFont(font); //设置字体

        cellStyle.setFillBackgroundColor(HSSFColor.BLUE.index);
        cell.setCellStyle(cellStyle);

        cell.setCellValue("商品信息汇总");
        //创建副标题列
        HSSFRow titleRow = sheet.createRow(1);

        for (int i = 0; i <declaredFields.length ; i++) {
            HSSFCell titleCell = titleRow.createCell(i);
            titleCell.setCellStyle(cellStyle);
            titleCell.setCellValue(declaredFields[i].getName());//给当前单元格设置字段名称

        }

        for (int i = 0; i < products.size() ; i++) {
            HSSFRow dataRow = sheet.createRow(i+2);



            //遍历对象的字段
            for (int j = 0; j < declaredFields.length ; j++) {

                HSSFCell fieldCell = dataRow.createCell(j);
                fieldCell.setCellStyle(cellStyle);

                //反射获取信息
                String getMethodName = "get"+declaredFields[j].getName().substring(0,1).toUpperCase()
                        + declaredFields[j].getName().substring(1);

                //调用方法
                Method declaredMethod = Product.class.getDeclaredMethod(getMethodName, new Class[]{});
                //指定GET方法
                Object invoke = declaredMethod.invoke(products.get(i), new Object[]{});
                System.out.println(invoke.toString());
                if(declaredFields[j].getType() == Date.class){
                    fieldCell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(invoke));
                }else {

                    fieldCell.setCellValue(invoke.toString());
                }
            }

        }

        //将excel输出到哪个文件中
        FileOutputStream stream = new FileOutputStream(new File("F:/a.xls"));
        workbook.write(stream);
        stream.close();
        workbook.close();
        return "aa";
        }
}